#include <stdio.h>
#include <stddef.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>

// 定义一个嵌套结构体
struct Address {
    char city[20];
    int zipCode;
    double latitude; // 新增 double 类型
};

// 定义一个 Friend 结构体（柔性数组的元素类型）
struct Friend {
    char name[20];
    int age;
};

// 定义一个包含多种数据类型的结构体
struct Person {
    char name[20];              // 字符数组
    int age;                    // 整型
    float height;               // 浮点型
    double weight;              // 双精度浮点型
    char *phoneNumber;          // 字符指针
    int scores[3];              // 整型数组
    struct Address addresses[3]; // 嵌套结构体数组
    unsigned char flags;        // 无符号字符
    void *metadata;             // void* 指针
    struct Friend friends[];    // 柔性数组（结构体类型）
};

// 定义 FieldInfo 结构体
struct FieldInfo {
    const char *name;            // 字段名称
    size_t offset;               // 字段在结构体中的偏移量
    size_t size;                 // 字段的大小.如果是柔性数组，这里是一个对象的大小
    int num;                     // 除char数组外，其他数组的数量（结构体或柔性数组）； 其他数据类型填1
    bool isFlex;                 // 是否柔性数组。0：不是，1：是
    const void *nestedStructDef; // 指向嵌套结构体的定义（如果是嵌套结构体）
};

// 打印字段的实际内容
void printFieldInfo(const void *base, const char *fieldName, size_t offset, size_t size) {
    const unsigned char *bytes = (const unsigned char *)base + offset;
    printf("Field: %-15s | Offset: %-4zu | Bytes: ", fieldName, offset);
    for (size_t i = 0; i < size; i++) {
        printf("%02x ", bytes[i]); // 以十六进制格式打印每个字节
    }
    printf("\n");
}

// 打印指针指向的实际内容
void printPointerContent(const void *base, const char *fieldName, size_t offset, size_t size) {
    const unsigned char *pointer = *(const unsigned char **)((const unsigned char *)base + offset);
    printf("Field: %-15s | Offset: %-4zu | Bytes: ", fieldName, offset);
    for (size_t i = 0; i < size; i++) {
        printf("%02x ", pointer[i]); // 以十六进制格式打印每个字节
    }
    printf("\n");
}

// 递归打印结构体字段
void printStructFields(const void *base, const char *structName, const struct FieldInfo *fields, size_t structSize) {
    printf("=== Struct: %s ===\n", structName);
    printFieldInfo(base, structName, 0, structSize);

    for (size_t i = 0; fields[i].name != NULL; i++) {
        if (fields[i].isFlex == true) {
            const unsigned char *flexibleArrayBase = (const unsigned char *)base + fields[i].offset;
            for (size_t j = 0; j < fields[i].num; j++) {
                char elementName[128];
                snprintf(elementName, sizeof(elementName), "%s[%zu]", fields[i].name, j);
                printStructFields(flexibleArrayBase + j * fields[i].size, elementName, (const struct FieldInfo *)fields[i].nestedStructDef, fields[i].size);
            }
        } else if (fields[i].nestedStructDef != NULL) {
            const unsigned char *nestedBase = (const unsigned char *)base + fields[i].offset;
            size_t nestedSize = fields[i].size;
            if (fields[i].num > 1) {
                for (size_t j = 0; j < fields[i].num; j++) {
                    char elementName[50];
                    snprintf(elementName, sizeof(elementName), "%s[%zu]", fields[i].name, j);
                    printStructFields(nestedBase + j * nestedSize, elementName, (const struct FieldInfo *)fields[i].nestedStructDef, nestedSize);
                }
            } else {
                printStructFields(nestedBase, fields[i].name, (const struct FieldInfo *)fields[i].nestedStructDef, nestedSize);
            }
        } else if (strcmp(fields[i].name, "phoneNumber") == 0 || strcmp(fields[i].name, "metadata") == 0) {
            // 处理指针类型的字段
            printPointerContent(base, fields[i].name, fields[i].offset, fields[i].size);
        } else {
            // 处理普通字段
            printFieldInfo(base, fields[i].name, fields[i].offset, fields[i].size);
        }
    }
}

int main() {
    // 动态分配内存以支持柔性数组
    size_t friendsCount = 3;
    size_t personSize = sizeof(struct Person) + friendsCount * sizeof(struct Friend);
    struct Person *rsp = (struct Person *)malloc(personSize);
    if (rsp == NULL) {
        perror("Failed to allocate memory");
        return 1;
    }
    // 初始化结构体实例
    strcpy(rsp->name, "Alice");
    rsp->age = 25;
    rsp->height = 1.75f;
    rsp->weight = 60.5;
    rsp->phoneNumber = "1234567890";
    rsp->scores[0] = 90;
    rsp->scores[1] = 85;
    rsp->scores[2] = 95;

    // 初始化嵌套结构体数组
    for (size_t i = 0; i < 3; i++) {
        snprintf(rsp->addresses[i].city, sizeof(rsp->addresses[i].city), "City%d", (int)(i + 1));
        rsp->addresses[i].zipCode = 10000 + (int)i;
        rsp->addresses[i].latitude = 40.0 + (double)i;
    }

    rsp->flags = 0xAB;

    // 初始化 void* 指针
    char abc[128] = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
    rsp->metadata = abc;

    // 初始化柔性数组（结构体类型）
    for (size_t i = 0; i < friendsCount; i++) {
        snprintf(rsp->friends[i].name, sizeof(rsp->friends[i].name), "Friend%d", (int)(i + 1));
        rsp->friends[i].age = 20 + (int)i;
    }

    // 定义 Person 结构体的字段信息（包含嵌套的 Address 数组和 Friend 柔性数组）
    const struct FieldInfo rspFields[] = {
        {"name", offsetof(struct Person, name), sizeof(rsp->name), 1, false, NULL},
        {"age", offsetof(struct Person, age), sizeof(rsp->age), 1, false, NULL},
        {"height", offsetof(struct Person, height), sizeof(rsp->height), 1, false, NULL},
        {"weight", offsetof(struct Person, weight), sizeof(rsp->weight), 1, false, NULL},
        {"phoneNumber", offsetof(struct Person, phoneNumber), strlen(rsp->phoneNumber) + 1, 1, false, NULL},
        {"scores", offsetof(struct Person, scores), sizeof(rsp->scores), 1, false, NULL},
        {"addresses", offsetof(struct Person, addresses), sizeof(rsp->addresses), 3, false, (const struct FieldInfo[]){
            {"city", offsetof(struct Address, city), sizeof(rsp->addresses[0].city), 1, false, NULL},
            {"zipCode", offsetof(struct Address, zipCode), sizeof(rsp->addresses[0].zipCode), 1, false, NULL},
            {"latitude", offsetof(struct Address, latitude), sizeof(rsp->addresses[0].latitude), 1, false, NULL},
            {NULL, 0, 0, 0, false, NULL} // 结束标记
        }}, // 嵌套结构体数组
        {"flags", offsetof(struct Person, flags), sizeof(rsp->flags), 1, false, NULL},
        {"metadata", offsetof(struct Person, metadata), strlen(abc) + 1, 1, false, NULL},
        {"friends", offsetof(struct Person, friends), sizeof(struct Friend), 3, true, (const struct FieldInfo[]){
            {"name", offsetof(struct Friend, name), sizeof(rsp->friends[0].name), 1, false, NULL},
            {"age", offsetof(struct Friend, age), sizeof(rsp->friends[0].age), 1, false, NULL},
            {NULL, 0, 0, 0, false, NULL} // 结束标记
        }}, // 柔性数组（结构体类型）
        {NULL, 0, 0, 0, false, NULL} // 结束标记
    };

    // 打印结构体中的所有字段（包括嵌套结构体数组和柔性数组）
    printStructFields(rsp, "Rsp", rspFields, sizeof(struct Person));

    // 释放动态分配的内存
    free(rsp);

    return 0;
}